﻿using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.Models;
using Flurl.Http;
using Newtonsoft.Json;

namespace CarAppClient.Helpers
{
    /// <summary>
    /// Http请求
    /// </summary>
    public class HttpHelper<T>
    {
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        private static string? GetToken()
        {
            var cacheService = AutoFacHelper.Instance.Get<ICacheService>();
            var token = cacheService.Get(CacheKey.AccessToken);
            if (string.IsNullOrEmpty(token))
            {
                return null;
            }
            return token;
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="checkToken"></param>
        /// <returns></returns>
        public static async Task<ApiResult<T>> GetAsync(string url, bool checkToken = true)
        {
            try
            {
                string responseStr = "";
                if (checkToken)
                {
                    var token = GetToken();
                    if (token == null)
                    {
                        return new ApiResult<T> { Code = StatusCodeEnum.Unauthorized, Message = "请重新登录" };
                    }
                    //return await url.WithOAuthBearerToken(token).GetAsync().ReceiveJson<ApiResult<T>>();//如果返回结果包含数组，ReceiveJson转换失败
                    responseStr = await url.WithOAuthBearerToken(token).GetAsync().ReceiveString();
                }
                else
                {
                    responseStr = await url.GetAsync().ReceiveString();
                }
                
                return JsonConvert.DeserializeObject<ApiResult<T>>(responseStr);
            }
            catch (Exception ex)
            {
                return new ApiResult<T> { Code = StatusCodeEnum.Error, ErrorMsg = "客户端请求失败" };
            }
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="t"></param>
        /// <param name="checkToken"></param>
        /// <returns></returns>
        public static async Task<ApiResult<T>> PostAsync<T2>(string url, T2 t, bool checkToken = true)
        {
            try
            {
                string responseStr = "";
                if (checkToken)
                {
                    var token = GetToken();
                    if (token == null)
                    {
                        return new ApiResult<T> { Code = StatusCodeEnum.Unauthorized, Message = "请重新登录" };
                    }

                    responseStr=await url.WithOAuthBearerToken(token).PostJsonAsync(t).ReceiveString();
                }
                else
                {
                    responseStr = await url.PostJsonAsync(t).ReceiveString();
                }
                
                return JsonConvert.DeserializeObject<ApiResult<T>>(responseStr);
            }
            catch (Exception ex)
             {
                return new ApiResult<T> { Code = StatusCodeEnum.Error, ErrorMsg = "客户端请求失败" };
            }
        }

        /// <summary>
        /// Put请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="t"></param>
        /// <param name="checkToken"></param>
        /// <returns></returns>
        public static async Task<ApiResult<T>> PutAsync<T2>(string url, T2 t, bool checkToken = true)
        {
            try
            {
                if (checkToken)
                {
                    var token = GetToken();
                    if (token == null)
                    {
                        return new ApiResult<T> { Code = StatusCodeEnum.Unauthorized, Message = "请重新登录" };
                    }
                    return await url.WithOAuthBearerToken(token).PutJsonAsync(t).ReceiveJson<ApiResult<T>>();
                }

                return await url.PutJsonAsync(t).ReceiveJson<ApiResult<T>>();
            }
            catch (Exception ex)
            {
                return new ApiResult<T> { Code = StatusCodeEnum.Error, ErrorMsg = "客户端请求失败" };
            }
        }

        /// <summary>
        /// Delete请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="checkToken"></param>
        /// <returns></returns>
        public static async Task<ApiResult<T>> DeleteAsync(string url, bool checkToken = true)
        {
            try
            {
                if (checkToken)
                {
                    var token = GetToken();
                    if (token == null)
                    {
                        return new ApiResult<T> { Code = StatusCodeEnum.Unauthorized, Message = "请重新登录" };
                    }
                    return await url.WithOAuthBearerToken(token).DeleteAsync().ReceiveJson<ApiResult<T>>();
                }

                return await url.DeleteAsync().ReceiveJson<ApiResult<T>>();
            }
            catch (Exception ex)
            {
                return new ApiResult<T> { Code = StatusCodeEnum.Error, ErrorMsg = "客户端请求失败" };
            }
        }
    }
}
